package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.media.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsMaterial;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.common.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 查询所有自媒体文章
     *
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1.参数检查
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数有误");
        }
        dto.checkParam();
        //2.条件查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //频道id
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //文章状态
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //发布时间 >= 开始时间
        if (dto.getBeginPubDate() != null) {
            wrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        //发布时间 <= 开始时间
        if (dto.getEndPubDate() != null) {
            wrapper.le(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        //当前自媒体人的文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        //按照创建日期倒排
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //分页构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //返回查询封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());

        //处理文章图片
        pageResponseResult.setHost(webSite);
        return pageResponseResult;


    }

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1.检查参数  封装wmNews对象
        WmNews wmNews = parseDtoToWmNews(dto);
        // 2.保存或修改文章
        saveOrUpdateWmNews(wmNews);
        //3.保存文章内容 或封面  和素材的关联关系


        //3.1 TODO 从文章内容中抽取所有的素材路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());
        //3.2 TODO 保存文章内容引用素材的关联关系
        saveRelativeInfo(materialUrls, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);

        //3.3 TODO 保存封面引用素材的关联关系
        saveRelativeInfoForCover(materialUrls, wmNews, dto);
        // 3.4 发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());


        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {

        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));

        //5. 上下架发送消息通知  用于同步article 及 elasticsearch
        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage() - 1) * dto.getSize());

        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }
        //分页查询
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        PageResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVOList);

        result.setHost(webSite);
        return result;

    }

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
    //1.参数检查
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser =null;
        if (wmNews.getUserId() !=null){
             wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        if (wmUser != null){
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVO);
        responseResult.setHost(webSite);

        return responseResult;
    }


    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
    //1.参数检查
        if (dto ==null || dto.getId() ==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //检查文章状态不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"文章已经发布了");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //TODO 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存文章封面和素材的关联关系
     *
     * @param materialUrls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> materialUrls, WmNews wmNews, WmNewsDTO dto) {
        //判断前端是否传热type是否为-1
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = materialUrls.size();
            if (size == 0) {
                //           * 内容中没有图片，则为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (size <= 2) {
                //            * 内容图片的个数小于等于2  则为单图截图一张图
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else {
                //              内容图片大于2，则为多图，截图三张图

                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            //           需要自动生成封面 规则:
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(imagesToStr(images));
            }
            //修改文章
            this.updateById(wmNews);
        }
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            //调用保存关系方法
            saveRelativeInfo(images, wmNews, WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    /**
     * 保存素材和文章管来奶关系的方法
     *
     * @param materialUrls       =素材的路径list
     * @param wmNews             文章
     * @param wmContentReference 引用类型 0 内容引用  1 封面引用
     */
    private void saveRelativeInfo(List<String> materialUrls, WmNews wmNews, Short type) {
        //1.先根据素材路径集合 查询素材表  得到对应的id集合
      /*  List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        .in(WmMaterial::getUrl, materialUrls)
                        //只返回ID字段的值
                        .select(WmMaterial::getId)
        );*/
        List<Integer> integers = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());

        //2. 判断id集合的数量 是否 等于 素材路径集合的数量  不等于提示素材丢失
        if (integers.size() < materialUrls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "相关素材缺失,保存文章失败");
        }
        // wmNewsMaterialMapper.saveRelations(wmMaterials,wmNews,type);
        //3.批量的插入
      /*  for (WmMaterial wmMaterial : wmMaterials) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }*/
        wmNewsMaterialMapper.saveRelations(integers, wmNews.getId(), type);

    }

    /**
     * 提取出内容中 锁涉及的素材路径
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {

        List<Map> maps = JSON.parseArray(content, Map.class);

        return maps.stream()  //创建流
                //集合中找到所有type 为amage 的amp
                .filter(map -> "image".equals(map.get("type")))
                //获取map的value字段
                .map(x -> x.get("value").toString())
                //替换带哦路径的前缀
                .map(url -> url.replaceAll(webSite, ""))
                //去除重复的素材
                .distinct()
                .collect(Collectors.toList());
        // 将得到的素材返回路径集合
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        //2.1  wmNews信息补全 (创建时间 上下架  发表用户id)
        wmNews.setCreatedTime(new Date());
//当 文章状态 9
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //2.2判断id是否为空, 为空保存wmNews
        if (wmNews.getId() == null) {
            this.save(wmNews);
        } else {
            //2.3如果不为空  修改wmNews  修改前要先将文章 和素材的关联关系删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            this.updateById(wmNews);
        }

    }

    private WmNews parseDtoToWmNews(WmNewsDTO dto) {
        //1.1 检查内容  标题 是否登录
        if (StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章的标题和内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //1.2dto拷贝属性wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //1.3type :如果type为-1 暂时将wmNews中的type设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //1.4  dto中的images是list  wmNews的images是字符串
        List<String> images1 = dto.getImages();
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            String images = imagesToStr(dto.getImages());
            wmNews.setImages(images);
        }
        //1.5补全id
        wmNews.setUserId(user.getId());
        return wmNews;
    }

    /**
     * 将字符串集合转为 字符串 字符串用都好拼接
     *
     * @param images
     * @return
     */
    private String imagesToStr(List<String> images) {
        return images.stream() //创建流对象
                //替换路径中的访问前缀
                .map(url -> url.replaceAll(webSite, ""))
                //将字符串使用逗号拼接
                .collect(Collectors.joining(","));
    }
}
